import { createRouter, createWebHistory, type RouteRecordRaw } from "vue-router";
import NotFound from '@/views/other/not-found.vue'
import Authentication from '@/views/authentication/index.vue'
import Login from '@/views/authentication/login.vue'
import RouterContainer from '@/components/router-container.vue'
import Dashboard from '@/views/dashboard/dashboard.vue'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useTagStore } from "@/stores/tag";
import storage from "@/storage";
import { StorageConst } from "@/constant";
import DynamicRouterHelper from "@/common/dynamicRouterHelper";
import type { SysMenuEx } from "@/types/sys-menu-tree";

export const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 认证页
    {
      path: "/authentication",
      name: "authentication",
      component: Authentication,
      children: [
        {
          path: "",
          name: "login",
          component: Login
        }
      ],
      meta: { hideLayout: true }
    },
    // 首页-仪表盘页面
    {
      path: "/",
      name: "home",
      component: RouterContainer,
      meta: { title: "仪表盘" },
      children: [
        {
          path: "",
          name: "dashboard",
          component: Dashboard
        }
      ]
    },
    // 商品模块
    {
      path: "/goods",
      name: "goods",
      component: RouterContainer,
      meta: { title: "商品管理" },
      children: [
        {
          path: "",
          name: "goodsList",
          component: () => import("@/views/goods/goods-list.vue"),
          meta: { title: "商品列表" },
        },
        {
          path: "add",
          name: "addGoods",
          component: () => import("@/views/goods/goods-save.vue"),
          meta: { title: "添加商品" },
        },
        {
          path: "classification-list",
          name: "classificationList",
          component: () => import("@/views/goods/classification-list.vue"),
          meta: { title: "商品分类" }
        }
      ]
    },
    // 订单模块
    {
      path: "/order",
      name: "order",
      component: RouterContainer,
      meta: { title: "订单管理" },
      children: [
        {
          path: "",
          name: "orderList",
          component: () => import("@/views/order/order-list.vue"),
          meta: { title: "订单列表" },
        }
      ]
    },
    // 权限管理模块
    {
      path: "/permission",
      name: "permission",
      component: RouterContainer,
      meta: { title: "权限管理" },
      children: [
        {
          path: "",
          name: "userManage",
          component: () => import("@/views/permission/user-manage.vue"),
          meta: { title: "用户管理" }
        },
        {
          path: "roles",
          name: "roleManage",
          component: () => import("@/views/permission/role-manage.vue"),
          meta: { title: "角色管理" }
        },
        {
          path: "menu",
          name: "menuManage",
          component: () => import("@/views/permission/menu-manage.vue"),
          meta: { title: "菜单管理" }
        },
        {
          path: "department",
          name: "departmentManage",
          component: () => import("@/views/permission/department-manage.vue"),
          meta: { title: "部门管理" }
        },
      ]
    },
    // 404 错误页 必须放到最后
    {
      path: '/:catchAll(.*)*',
      name: NotFound.name,
      component: NotFound,
      meta: { hideLayout: true }
    }
  ],
});

const filterRouter = ["authentication", "login"];

router.beforeEach((to, from, next) => {
  // 校验是否登录
  if (!filterRouter.includes(to.name as string)) {
    const token = storage.getItem(StorageConst.Token);
    if (!token) {
      next("/authentication");
      return
    }
  }

  // 处理路由标签
  const tagSotre = useTagStore();
  if (!tagSotre.checkTagRepeat(to.path)) {
    const tag = {
      title: to.meta.title as string,
      path: to.fullPath as string,
      name: to.name as string
    }
    if (tagSotre.addTagRoute(tag)) {
      return
    }
  }
  NProgress.start();
  next();
});

router.afterEach((to, from) => {
  NProgress.done();
});

// 递归组装路由树
const recursionRouters = (data: SysMenuEx[], parent?: SysMenuEx): RouteRecordRaw[] => {
  const modules = import.meta.glob('../views/**/*.vue');
  
  return data.map(x => {
    const path = DynamicRouterHelper.splicePath([parent?.frontEndRouter || "", x.frontEndRouter]);
    const asyncComponent = modules[`../views/${x.componentPath}.vue`];
    // const asyncComponent = () => import(/* @vite-ignore */`@/views/${x.componentPath}.vue`);
    // 仪表盘页面直接使用组件不异步加载
    const isHome = path === "/";
    return {
      path,
      name: DynamicRouterHelper.pathToName(path),
      // 组件路径不存在时
      component: x.componentPath ? (isHome ? Dashboard : asyncComponent) : RouterContainer,
      meta: { title: x.name },
      children: x.children && x.children.length && recursionRouters(x.children, x) || []
    }
  });
}

// 初始化动态路由
export const initRouters = () => {
  DynamicRouterHelper.initRouters(window._menuListCache || [], router);
}
